// 全局请求封装
// const base_url = 'http://10.160.151.6:8080/api'
// const base_url = 'http://192.168.254.133:80/api'
const base_url = 'http://xuanhao.free.idcfengye.com/api'
// 请求超出时间
const timeout = 5000

// 需要修改token，和根据实际修改请求头
export default (params) => {
	let url = params.url;
	let method = params.method || "get";
	let data = params.data || {};
	let responseType = params.responseType;
	let header = {
		// 'Blade-Auth': uni.getStorageSync('token') || '',
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': 'Basic ' + uni.getStorageSync('token') || '',
		...params.header
	}
	if (method == "post") {
		header = {
			'Content-Type': 'application/json'
		};
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + url,
			method: method,
			responseType: responseType,
			header: header,
			data: data,
			timeout,
			success(response) {
				const res = response
				if (res.statusCode == 200 || (res.data.code >= 200 && res.data.code <=400)) {
					resolve(res.data);
				} else {
					// uni.clearStorageSync()
					switch (res.statusCode) {
						case 401:
							uni.showModal({
								title: "提示",
								content: "请登录",
								showCancel: false,
								success() {
									setTimeout(() => {
										uni.navigateTo({
											url: "/pages/login/login",
										})
									}, 1000);
								},
							});
							break;
						case 404:
							uni.showToast({
								title: '请求地址不存在...',
								duration: 2000,
							})
							break;
						default:
							uni.showToast({
								title: res.data.msg,
								icon:"error",
								duration: 2000,
							})
							break;
					}
				}
			},
			fail(err) {
				// if (err.errMsg.indexOf('request:fail') == -1) {
				if (err.errMsg === 'request:fail') {
					uni.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					})
				} else {
					uni.showToast({
						title: '未知异常',
						icon: "error",
						duration: 2000
					})
				}
				reject(err);

			},
			complete() {
				setTimeout(()=> {
					uni.hideLoading();
					uni.hideToast();
				}, 1000);
			}
		});
	}).catch(() => {});
};